<?php
namespace app\admin\controller;
use think\Controller;	//引入Controller类
use app\admin\model\Users as UsersModel;
use think\Session;
use think\captcha\Captcha;
use app\common; //引入公共文件

class Login extends Controller
{
    // 登录页面
    public function index(){
        if(Session::has('username') && Session::get('type')=='admin' && Session::get('login_type')=='2'){
            $this->redirect('/admin');
        }else{
            return $this->fetch();
        }
    }

    // 登录ajax验证
    public function loginCheck(){
        if($_POST){
            $code = $_POST['code'];
            $captcha = new Captcha();
            $username = $_POST['username'];
            $password = encryptDecrypt($_POST['password'],0);
            $UsersModel = new UsersModel();
            $resule = $UsersModel->loginCheck($username);
            // var_dump($resule);
            if (empty($resule)) echo 'no_user';    //用户不存在
            elseif ($resule['login_type'] != 2) echo 'no_admin';    //用户不是管理员
            elseif ($resule['password'] != $password) echo 'no_pass';   //用户密码错误
            elseif (!$captcha->check($code)) echo 'Verify_code_error';  //验证码错误
            else{
                $last_login = $UsersModel->last_login($resule['username'],$resule['last_login']); //记录本次和上次登陆时间
                if(!$last_login) echo 'no_network';
                else
                Session::set('username',$resule['username']);
                Session::set('type','admin');
                Session::set('login_type',$resule['login_type']);
                Session::set('Name',$resule['Name']);
                echo 'yes';
            };
        }
    }

    // 登出
    public function logout(){
        Session::delete('username');
        Session::delete('type');
        Session::delete('login_type');
        $this->redirect('/admin/login');
    }
}